<?php

/**
 *  This script returns a JSON string containing the informations 
 *  about the currently logged in FB user and his/her friends.
 *  
 *  INPUT:
 *  Doesn't need any query parameter, only the session data are required, 
 *  according to which the currently logged in user can be determined.
 *  
 *  OUTPUT:
 *  JSON string representation of an 2 element associative array with keys "user" and "friends". 
 *  The value of the "friends" element is an array. Each element of the "friends" array and the "user" element has the following fields:
 *  <li>uid			[string]	- ID of the user (logged in user/friend) 
 *  <li>name        [string]	- full name
 *  <li>profile_pic [string]	- url of the profile picture; empty string if not specified
 *  <li>longitude   [string]	- longitude part of the last known location; null if the location is not specified
 *  <li>latitude    [string]	- latitude part of the last known location; null if the location is not specified
 *  <li>address		[string]	- the address of the last known location; null if the location is not specified
 *  <li>note        [string]	- note stored with the last known location; null if the location is not specified
 *  <li>timestamp   [string]	- Facebook-like "... ago" timestamp when the location was updated; null if the location is not specified
 *  <li>distance    [array]     - !ONLY IN CASE OF FRIENDS, NOT IN CASE OF USER! the distance of the friend from the user, according to the last known locations. 
 *                              - "value" - distance value; null if the location is not specified
 *                              - "units" - units of the distance value; "km", "m" or null if the location is not specified
 *  
 *  Note: the [string] format means JSON's string format, so including the white and special char formattings,
 *  e.g. '/' -> '\/', '\' -> '\\', ...etc. See http://www.json.org/ for the full specification.
 * 
 * Return JSON string sample: 
 * {
 *  "user":{"uid":"1781804022","name":"Moln\u00e1r Ladislav","profile_pic":"","longitude":"21.268087527275","latitude":"48.755565644982","address":"Budape\u0161tianska 7, 04013 S\u00eddlisko \u0164ahanovce, Slovakia","note":"text","timestamp":"2 weeks ago"},
 *  "friends":[
 *      {"uid":"100000427871954","name":"Jeff Zhao","profile_pic":"http:\/\/profile.ak.fbcdn.net\/v22939\/1129\/70\/q100000427871954_3660.jpg","longitude":"104.0","latitude":"30.55044651031494","address":"China Chengdu Shuangliu\u5927\u4ef6\u8def\u957f\u57ce\u8def\u53e3\u7ad9","note":"this is a test note","timestamp":"1 day ago","distance":{"value":"7007","units":"km"}},
 *      {"uid":"1014450671","name":"Radovan Stas","profile_pic":"http:\/\/profile.ak.fbcdn.net\/profile5\/1056\/79\/q1014450671_4160.jpg","longitude":"21.258957592104","latitude":"48.722087534532","address":"Gymn\u00e1zium na Kov\u00e1\u010dskej ulici, 04001 Ko\u0161ice, Slovakia","note":"Railway","timestamp":"1 week ago","distance":{"value":"3.8","units":"km"}},
 *      {"uid":"100000158900525","name":"Miro Jookie Nohaj","profile_pic":"http:\/\/profile.ak.fbcdn.net\/v22942\/851\/55\/q100000158900525_977.jpg","longitude":"21.250135074677","latitude":"48.72318953696","address":"Pri Jazdiarni 3, 04001 Ko\u0161ice - Star\u00e9 Mesto-Star\u00e9 Mesto, Slovakia","note":"I'm waiting for you here.","timestamp":"1 week ago","distance":{"value":"3.8","units":"km"}},
 *      {"uid":"100000024471694","name":"Situare Dev","profile_pic":"http:\/\/profile.ak.fbcdn.net\/v225\/1010\/122\/q100000024471694_1883.jpg","longitude":"21.25027298927307","latitude":"48.71764898300171","address":"\u010cajakova 1192\/2, 04001 Ko\u0161ice - Star\u00e9 Mesto-Star\u00e9 Mesto, Slovakia","note":"Enter your automation message here...","timestamp":"2 weeks ago","distance":{"value":"4.4","units":"km"}},
 *      {"uid":"1799083725","name":"Lucia \u0160tigov\u00e1","profile_pic":"http:\/\/profile.ak.fbcdn.net\/v226\/766\/49\/q1799083725_3920.jpg","longitude":"21.248397555549","latitude":"48.713517179774","address":"\u017di\u017ekova 2340\/29, 04001 Ko\u0161ice - Juh-Juh, Slovakia","note":"I live here.... Waiting for visit...","timestamp":"3 weeks ago","distance":{"value":"4.9","units":"km"}},
 *      {"uid":"1127850689","name":"Jan Magur","profile_pic":"http:\/\/profile.ak.fbcdn.net\/v230\/539\/101\/q1127850689_8143.jpg","longitude":null,"latitude":null,"address":null,"note":null,"timestamp":null,"distance":{"value":null,"units":null}}
 *  ]
 * }
 */
header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');

try {
    include_once './log4php/Logger.php';
    include_once './User.php';
    include_once './Situare.php';
    include_once './I18N.php';
    include_once './Distance.php';
    include_once './Error.php';
    include_once './Utils.php';
    include_once './constants.php';

    // initialize logging
    Logger::configure('./log4j.properties');

    $log = Logger::getLogger(basename(__FILE__));
    $log->debug('[START] ' . basename(__FILE__));

    $START_TIME = microtime(TRUE);

    // read the input params
    $inputArray = Utils::getInputParameters();
    $api = Utils::getInputParameterValue($inputArray, PARAM_API, NULL);
    $extraUserData = array();
    if (isset($inputArray[PARAM_USER_EXTRA_DATA])) {
        $extraUserData = explode(',', $inputArray[PARAM_USER_EXTRA_DATA]);
    }

    $situare = new Situare();    
    
    // in case of invalid session
    if (!$situare->isValidSession()) {
        $log->debug('$_COOKIE[] = ' . Utils::toString($_COOKIE));
        $log->debug('$_POST[] = ' . Utils::toString($_POST));
        $log->debug('$_GET[] = ' . Utils::toString($_GET));
        throw new SituareException(
                "Not found valid session data!",
                ERROR_SESSION_INVALID_OR_MISSING);
    }

    try {
        // get the currently logged in user
        $user = $situare->getUser($extraUserData);
    }
    catch (FacebookApiException $e) {
        if ($e->getCode() == 602) { // wrong extra column name
            throw new SituareException(
                    $e->getMessage(),
                    ERROR_GETLOCATION_WRONG_EXTRA_FIELD);
        }
    }

    // build up the array holding the user data
    $userData = array();
    $userData['uid'] = $user->fb_uid;
    $userData['name'] = $user->fb_name;
    $userData['profile_pic'] = $user->fb_pic_url;
    $userData['longitude'] = isset($user->fb_location) ? $user->fb_location->lon : null;
    $userData['latitude'] = isset($user->fb_location) ? $user->fb_location->lat : null;
    $userData['address'] = isset($user->fb_location) ? $user->fb_location->address : null;
    $userData['note'] = isset($user->fb_location) ? $user->fb_location->data : null;
    $userData['timestamp'] = isset($user->fb_location) ? I18N::epochToAgo($user->fb_location->timestamp, FALSE) : null;

    foreach ($extraUserData as $extraDataKey) {
        $userData[$extraDataKey] = $user->getExtraData($extraDataKey);
    }

    // get the list of friends and build up the array filled with friends data, location, distance, etc...
    $friends = $user->getFriends();
    $friendsArray = array();
    foreach ($friends as $key => $friend) {
        $friendData = array();
        $friendData['uid'] = $friend->fb_uid;
        $friendData['name'] = $friend->fb_name;
        $friendData['profile_pic'] = $friend->fb_pic_url;
        $friendData['longitude'] = isset($friend->fb_location) ? $friend->fb_location->lon : null;
        $friendData['latitude'] = isset($friend->fb_location) ? $friend->fb_location->lat : null;
        $friendData['address'] = isset($friend->fb_location) ? $friend->fb_location->address : null;
        $friendData['note'] = isset($friend->fb_location) ? $friend->fb_location->data : null;
        $friendData['timestamp'] = isset($friend->fb_location) ? I18N::epochToAgo($friend->fb_location->timestamp, FALSE) : null;
        $friendData['distance'] = Distance::getDistanceArray($user, $friend);

        foreach ($extraUserData as $extraDataKey) {
            $friendData[$extraDataKey] = $friend->getExtraData($extraDataKey);
        }

        $friendsArray[] = $friendData;
    }

    // build up the result array containing the logged in user's data and his/her friends' data
    $resultArray = array();
    $resultArray['user'] = $userData;
    $resultArray['friends'] = $friendsArray;

    // create JSON string from the result array and return it
    $jsonStr = json_encode($resultArray);
    
    if ($api == API_2_0) {
        $response = Situare::getApi20Response($resultArray);
        echo $response;
        $log->debug('Result JSON string = ' . $response);
    }
    else {
        echo $jsonStr;
        $log->debug('Result JSON string = ' . $jsonStr);
    }
    
    $log->debug('[ END ] ' . basename(__FILE__));

    $END_TIME = microtime(TRUE);
    $log->debug('[PERF ] Total script execution took ' . ($END_TIME - $START_TIME) . "ms");
} catch (Exception $e) {
    $log->error("Exception:");
    $log->error("Code: " . $e->getCode());
    $log->error("Message: " . $e->getMessage());
    $log->error("Location: " . $e->getFile() . " at line " . $e->getLine());
    $log->error("Trace: " . $e->getTraceAsString());

    if ($api == API_2_0) {
        echo Situare::getApi20Response($e);
    }
    else  {
        echo getExceptionAsJson($e);
    }
}



?>